<?

/* --|	ACCOUNT
  Software: Socially
  Version: 1.0
  Contact: http://socially.googlecode.com
  Info: http://socially.googlecode.com
  Support: http://socially.googlecode.com
  --------------------------------------------------------------------------
  Author: goker.cebeci | http://gokercebeci.com
  --------------------------------------------------------------------------
  License: Distributed under the GNU General Public License (GPL)
  http://www.gnu.org/licenses/gpl.html
  This program is distributed in the hope that it will be useful - WITHOUT
  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  FITNESS FOR A PARTICULAR PURPOSE.
  ------------------------------------------------------------------------- */

class tag {

    public static function add($a) {
        $a['tag'] = strip_tags(addslashes(trim($a['tag'])));
        if (!$a['tag'])
            return common::result(400, _('Please enter a tag'), array('tag'));
        $r = db::query('INSERT INTO tag SET'
                        . sprintf("`tag` = '%s', ", $a['tag'])
                        . '`date` = NOW()
            ON DUPLICATE KEY UPDATE ID = ID, '
                        . sprintf("`tag` = '%s', ", $a['tag'])
                        . '`date` = NOW();');
        return db::insertid();
    }

    public static function info($tag, $ID = 0) {
        //if(!$tag) return common::result(400,_('Please enter a tag'),array('tag'));
        if($ID)
        $r = db::query(sprintf('SELECT * FROM tag WHERE ID = "%d" LIMIT 1', $ID), true);
        else
        $r = db::query(sprintf('SELECT * FROM tag WHERE tag = "%s" LIMIT 1', addslashes($tag)), true);

        $r->creator = db::query(sprintf('SELECT accountID FROM tags WHERE tagID = %d ORDER BY ID ASC LIMIT 1', $r->ID), true);
        $r->creator = profile::get(array('ID' => $r->creator->accountID));

        return $r;
    }

    public static function users($ID, $limit = 50) {
        $r = db::query(sprintf('SELECT accountID FROM tags WHERE tagID = %d LIMIT 50', $ID), true, true);
        if ($r)
            foreach ($r as $k => $i)
                $r[$k] = profile::get(array('ID' => $i->accountID));
        return $r;
    }

    public static function paste($a) {
        $ID = ($a['ID']) ? $a['ID'] : self::add($a);
        if (!$ID)
            return;
        db::query(sprintf("INSERT INTO tags (`accountID`, `tagID`)
                    VALUES ('%d', '%d');",
                                UID, $ID));
        cache::del("tag[list][" . UID . "]");
        return common::result(200, array('ID' => $ID, 'name' => $a['tag']));
    }

    public static function remove($a) {
        if (!$a['ID'])
            return common::result(400, _('ID empty!'));
        db::query(sprintf("DELETE FROM tags WHERE `accountID` = %d AND `tagID` = %d;",
                                UID, $a['ID']));
        cache::del("tag[list][" . UID . "]");
        return common::result(200, array('ID' => $a['ID']));
    }

    public static function get($a) {
        $r = cache::get("tag[list][" . $a['accountID'] . "]");
        if (!$r) {
            $r = db::query(sprintf('SELECT tag.ID, tag.tag FROM tag, tags WHERE tag.ID = tagID AND accountID = %d LIMIT %d', $a[accountID], TAG_MAX_LIMIT), 1, 1);
            cache::set("tag[list][" . $a['accountID'] . "]", $r);
        }
        if($a['tags'])
            foreach($r as &$i){
                if(in_array($i, $a['tags'])) $i->match = 1;
            }
        return $r;
    }

    public static function trends($limit) {
        return $r = db::query(sprintf('SELECT COUNT(tagID) as rank, tag.ID, tag.tag FROM tag, tags WHERE tag.ID = tagID GROUP BY tagID ORDER BY rank DESC LIMIT %d', $limit), 1, 1);
    }

    public static function share($a) {
        if (!$a['tagID'])
            return common::result(800, _('Requered value is empty'));
        // CHECK USER TAGS include the TAG
        //if(!$a['application']) return common::result(800,_('Requered value is empty'));
        if (!$a['post'])
            return common::result(400, _('Please enter a post'), array('post'));
        $a['post'] = strip_tags(addslashes(trim($a['post'])));
        // DETECT LINKS
        $a['post'] = preg_replace('/\bhttp\:\/\/[^\s]+/', '<a href="\\0" rel="nofollow">\\0</a>', $a['post']);
        $r = db::query(sprintf("INSERT INTO tagShares (`accountID`,`tagID`,`content`,`date`)
                    VALUES ('%d','%d','%s',NOW());",
                                UID, $a['tagID'], $a['post']));
        cache::del("tag[share][" . $a['tagID'] . "]");
        $i = db::query('SELECT * FROM tagShares WHERE ID = ' . db::insertid() . ';', true);
        $i->sender = profile::get(array('ID' => $i->accountID));
        $tpl = common::template('apps/tag/template/_share_item.html', $i);
        return common::result(200, json_encode($tpl));
    }

    public static function shareitem($ID) {
        $i = db::query(sprintf('SELECT * FROM tagShares WHERE ID = %d;',$ID), true);
        $i->sender = profile::get(array('ID' => $i->accountID));
        $i->comments = @array_reverse(comment::thread(array('app' => 'tag', 'itemID' => $i->ID, 'limit'=>5)));
        return $i;
        //$tpl = common::template('apps/tag/template/_share_item.html', $i);
        //return common::result(200, json_encode($tpl));
    }

    public static function shareremove($a) {
        if (!$a['ID'])
            return common::result(800, _('Requered value is empty'));
        $r = db::query(sprintf("DELETE FROM tagShares WHERE `ID` = %d", $a['ID'])
                        . (EDITOR ? ';' : sprintf(" AND `accountID` = %d;", UID)));
        cache::del("tag[share][" . $a['tagID'] . "]");
        return common::result(200, 'share' . $a['ID']);
    }

    public static function shares($ID) {
        //$r = cache::get("tag[share][$ID]");
        if (!$r) {
            $r = db::query(sprintf("SELECT * FROM tagShares WHERE tagID = %d ORDER BY `date` DESC LIMIT 31;", $ID), 1, 1);
            if ($r)
                foreach ($r as &$i) {
                    $i->sender = profile::get(array('ID' => $i->accountID));
                    $i->comments = @array_reverse(comment::thread(array('app' => 'tag', 'itemID' => $i->ID, 'limit'=>5)));
                }
            cache::set("tag[share][$ID]", $r);
        }
        return $r;
    }

    public static function talks($limit) {
        $t = db::query(sprintf("SELECT *, (SELECT tag FROM tag WHERE ID = tagID) as tag FROM tagShares
            WHERE tagID IN ( SELECT tagID FROM tags WHERE accountID = %d )
            ORDER BY `date` DESC LIMIT %d;", UID, $limit+1), true, true);
        if ($t)
            foreach ($t as &$i) {
                $i->sender = profile::get(array('ID' => $i->accountID));
                $i->comments = @array_reverse(comment::thread(array('app' => 'tag', 'itemID' => $i->ID, 'limit'=>3)));
            }
        return $t;
    }

    public static function delete($a) {
        if ($a['sender'])
            db::query(sprintf("UPDATE postieAttendees SET status = 2 WHERE senderID = %d AND conversationID = %d;", $a['UID'], $a['CID']));
        else
            db::query(sprintf("UPDATE postieAttendees SET status = 2 WHERE recipientID = %d AND conversationID = %d;", $a['UID'], $a['CID']));
        return common::result(200, array(303, $a['UID'], 0, $a['CID']));
    }

    public static function comment($a=false,$cmd = 'add'){
        switch ($cmd){
            case 'add':
                $c = comment::post(array('app'=>'tag','itemID'=>$a['itemID'],'senderID'=>$a['senderID'],'comment'=>$a['comment']));
                if($c) {
                    $owner = db::query(sprintf("SELECT accountID FROM tagShares WHERE ID = %d LIMIT 1;",$a['itemID']),true);
                    $owner = profile::get(array('ID'=>$owner->accountID));
                    $owner->status = profile::status($owner->accountID);
                    $sender = profile::get(array('ID'=>$a['senderID']));
                    if($owner->status == 'offline'){
                        //notification mail
                        $message = sprintf(_('You have a new comment on your %s sharing item $s from %s.')
                                ,'<a href="http://'.DOMAIN.'/tag/'.$a['itemID'].'">','</a>'
                                ,'<a href="http://'.DOMAIN.'/'.$sender->link.'">'.$sender->fullname.'</a>');
                        notification::mail(array(
                            'application'=>'photos',
                            'sender'=>$sender->ID,
                            'recipient'=>$owner->ID,
                            'message'=>$message
                            ));
                    } else {
                        notification::send(array(
                            'application'=>'tag',
                            'sender'=>$sender->ID,
                            'recipient'=>$owner->ID,
                            'item'=>$a['itemID'],
                            'notification'=>'sharing'
                            ));
                    }
                    $i = new stdClass();
                    $i->ID = $c;
                    $i->date = @date('Y-m-d H:i:s');
                    $i->comment = $a['comment'];
                    $i->sender = $sender;
                    return common::result(200,common::template('apps/postie/template/comment.html', null, null, $i),null,'/tag/'.$a['itemID'],true);
                }
            break;
        }
    }

    public static function notification($ID, $sender, $item = null) {
        $notification = array(
            'sharing' => sprintf(_('%s commented on your %ssharing item%s.')
                    , '<a href="http://' . DOMAIN . $sender->url . '">' . $sender->fullname . '</a>'
                    , '<a href="http://' . DOMAIN . '/tag/item/' . $item . '">', '</a>')
        );
        return $notification[$ID];
    }

}

?>